const WXAPI = require('../../wxapi/main')
const app = getApp()

Page({
  data: {
    userAvatar: '',
    userName: '',
    birthday: ''
  },

  onLoad(options) {
    this.setData({
      userAvatar: options.userAvatar,
      userName: options.userName,
      birthday: options.birthday || '2000-01-01' // 设置默认生日
    });
  },

  chooseImage: function() {
    const that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album'],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        that.setData({
          userAvatar: tempFilePaths[0]
        });
      }
    });
  },

  bindDateChange: function(e) {
    this.setData({
      birthday: e.detail.value
    });
  },

  editUser: function(e) {
    const data = {
      avatar: this.data.userAvatar,
      userName: this.data.userName,
      birthday: this.data.birthday
    };

    WXAPI.userModify(data).then(function(res) {
      if (res.code === 0) {
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 2000,
          success: function() {
            wx.navigateBack();
          }
        });
      } else {
        wx.showModal({
          title: '错误',
          content: res.msg,
          showCancel: false
        });
      }
    }).catch(function(err) {
      wx.showModal({
        title: '错误',
        content: '请求失败，请稍后重试',
        showCancel: false
      });
    });
  }
});